<template>
  <el-container>
    <el-header>
      <div>
        <el-form :inline="true">
          <el-form-item>
            <el-input placeholder="" v-model="search.queryValue" class="input-with-select" clearable>
              <template v-slot:prepend>
                <!-- slot="prepend" -->
                <el-select v-model="search.queryKey" placeholder="请选择" class="query-select" clearable>
                  <el-option label="租户名称" value="name"></el-option>
                  <el-option label="租户别名" value="alias"></el-option>
                  <el-option label="租户编码" value="code"></el-option>
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-header>
    <el-header>
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-plus" @click="add">创建渠道</el-button>
      </div>
      <div class="right-panel">
        <div class="right-panel-search">
          <el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="nopadding">
      <scTable
        ref="table"
        tableName="listCustomColumn"
        :apiObj="apiObj"
        :params="search"
        :column="column"
        row-key="id"
        @selection-change="selectionChange"
        stripe
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <!-- 是否启用/禁用 -->
        <template #disableoperator="scope">
          <el-switch
            v-model="scope.row.disable"
            style="--el-switch-on-color: var(--el-border-color); --el-switch-off-color: var(--el-color-primary)"
            class="ml-2"
            @change="disableChangeHandle(scope.row)"
          />
        </template>
        <!-- 是否自动监控 -->
        <template #automaticallyoperator="scope">
          <el-switch v-model="scope.row.controlAutomatically" class="ml-2" @change="automaticallyChangeHandle(scope.row)" />
        </template>

        <!-- 响应时间 可点击测试渠道 -->
        <template #reponseTimeoperator="scope">
          <el-tag
            class="tag-click"
            :key="scope.row.id"
            :type="scope.row.responseTimeStatus == 'N' ? 'info' : scope.row.responseTimeStatus == 'F' ? 'danger' : 'success'"
            effect="dark"
            @click="responseTimeClickEvent(scope.row.id)"
            round
          >
            {{ scope.row.responseTime == null ? '未测试' : scope.row.responseTime / 1000 + '秒' }}
          </el-tag>
        </template>

        <!-- 消耗总额 -->
        <template #quotaoperator="scope">
          <el-tag :key="scope.row.id" type="info" effect="dark" round>
            {{ moneyFormat(scope.row.quota) }}
          </el-tag>
        </template>

        <!-- 额度 -->
        <template #remainQuotaoperator="scope">
          <el-tag :key="scope.row.id" type="info" effect="dark" round>
            {{ moneyFormat(scope.row.remainQuota) }}
          </el-tag>
        </template>

        <!-- 权重，可输入改变权重 -->
        <template #orderoperator="scope">
          <el-input-number v-model="scope.row.order" :controls="false" style="width: 80px" :min="1" :max="100" @change="orderChangeHandle(scope.row)" />
        </template>

        <template #operator="scope">
          <el-button-group>
            <el-button text type="primary" size="small" @click="table_show(scope.row, scope.$index)">查看</el-button>
            <el-button text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
        </template>
      </scTable>
    </el-main>
  </el-container>

  <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSaveSuccess" @closed="dialog.save = false"></save-dialog>
</template>

<script>
import saveDialog from './save';

export default {
  name: 'AIChannelManage',
  components: {
    saveDialog,
  },
  data() {
    return {
      dialog: {
        save: false,
      },
      apiObj: this.$API.aiChannel.page,
      selection: [],
      search: {
        queryKey: '',
        queryValue: '',
      },
      column: [
        {
          label: '名称',
          prop: 'name',
          width: '150',
        },
        {
          label: '是否启用',
          prop: 'disableoperator',
          width: '100',
        },
        {
          label: '是否自动监控',
          prop: 'automaticallyoperator',
          width: '100',
        },
        {
          label: 'AI类型',
          prop: 'typeName',
          width: '150',
        },
        {
          label: '响应时间',
          prop: 'reponseTimeoperator',
          width: '150',
        },
        {
          label: '创建时间',
          prop: 'creationTime',
          width: '150',
        },
        {
          label: '消耗总额',
          prop: 'quotaoperator',
          width: '150',
        },
        {
          label: '额度',
          prop: 'remainQuotaoperator',
          width: '200',
        },
        {
          label: '权重',
          prop: 'orderoperator',
          width: '160',
        },
        {
          label: '操作',
          prop: 'operator',
          width: '170',
          fixed: 'right',
          align: 'right',
        },
      ],
    };
  },
  computed: {
    moneyFormat() {
      return function (row) {
        if (row == undefined) return '';
        // 计算金额
        return '$' + (row / 500000).toFixed(6);
      };
    },
  },
  methods: {
    //添加
    add() {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open();
      });
    },
    //编辑
    table_edit(row) {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open('edit').setData(row);
      });
    },
    //查看
    table_show(row) {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open('show').setData(row);
      });
    },

    //删除
    async table_del(row) {
      var res = await this.$API.aiChannel.remove.post(row.id);
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('删除成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },

    /**
     * 表格选择后回调事件
     * @param selection
     */
    selectionChange(selection) {
      this.selection = selection;
    },
    //搜索
    upsearch() {
      this.$refs.table.upData(this.search);
    },
    /**
     * 本地更新数据
     * @param data
     * @param mode
     */
    handleSaveSuccess(data, mode) {
      if (mode == 'add') {
        this.$refs.table.refresh();
      } else if (mode == 'edit') {
        this.$refs.table.refresh();
      }
    },
    /**
     * 权重改变时的事件
     */
    async orderChangeHandle(currentValue) {
      console.log(currentValue);
      var res = await this.$API.aiChannel.updateOrder.get(currentValue.id, currentValue.order);
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('操作成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },
    /**
     * 自动监控切换状态事件
     * @param currentValue
     */
    async automaticallyChangeHandle(currentValue) {
      var res = await this.$API.aiChannel.updateAutomatically.post({
        id: currentValue.id,
        status: currentValue.controlAutomatically,
      });
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('操作成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },
    /**
     * 禁用状态 切换事件
     * @param currentValue
     * @param oldValue
     */
    async disableChangeHandle(currentValue) {
      var res = await this.$API.aiChannel.updateDisable.post({
        id: currentValue.id,
        status: currentValue.disable,
      });
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('操作成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },
    /**
     * 渠道响应时间的点击时间
     * @param id 渠道id
     */
    async responseTimeClickEvent(id) {
      var res = await this.$API.aiChannel.test.get(id);
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('操作成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },
  },
};
</script>

<style>
.query-select {
  max-width: 100px;
}
.tag-click {
  cursor: pointer !important;
}
</style>
